package zozopo.search;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;
import org.wltea.analyzer.lucene.IKQueryParser;
import org.wltea.analyzer.lucene.IKSimilarity;

import zozopo.comm.Validate;
import zozopo.database.BusiDatabaseManager;
import zozopo.database.SqlMachine;
import zozopo.manual.operations.ReleaseTB;
import zozopo.operations.comm.OperatingService;

/**  
 * @author ht  
 * 查询  
 *  
 */  
public class Searcher extends OperatingService{
	
   private static int TOP_NUM = 100;//显示前100条结果   
   private static String FIELD_NAME = "content";//显示前100条结果   
   //private static int File indexDir;
   
   public Searcher(Connection conn){
		super(conn);
	}
	
	public Searcher(){
		this.databaseConnection = new BusiDatabaseManager();
		this.conn = databaseConnection.getConnection();
	}
     
/**查询  
 * @param indexDir  
 * @param q  
 * @throws Exception  
 */  
  public ArrayList<String> search(File indexDir,String searchstr) throws Exception {
	  
	ArrayList<String> idList = new ArrayList<String>();
	
    IndexSearcher is = new  IndexSearcher(FSDirectory.open(indexDir),true);//read-only   
    String field = FIELD_NAME;   
       
    QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field, new StandardAnalyzer(Version.LUCENE_CURRENT));//有变化的地方 
   
    Query query = parser.parse(searchstr); 
    
   /* BooleanQuery query = new BooleanQuery();
 
    query = getBooleanQuery(searchstr);
   // query.Add(query1, BooleanClause.Occur.MUST);
    //query.Add(query2, BooleanClause.Occur.MUST);*/

      
  
    TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM , false);//有变化的地方   
    long start = new Date().getTime();// start time   
    
    is.search(query, collector);   
    ScoreDoc[] hits = collector.topDocs().scoreDocs;   
 
   // System.out.println(hits.length);   
    for (int i = 0; i < hits.length; i++) { 
        Document doc = is.doc(hits[i].doc);//new method is.doc()
     // 若debug模式开启，则输出debug 信息
        if (logger.isDebugEnabled()) {
        	System.out.println(doc.getField("id")+"   "+hits[i].toString()+"  ");   
            System.out.println(doc.getField("id").stringValue()+"   "+hits[i].toString()+"  "); 
        }
        
        
        idList.add(doc.getField("id").stringValue());
    }   
    long end = new Date().getTime();//end time   
  
    
 // 若debug模式开启，则输出debug 信息
    if (logger.isDebugEnabled()) {
    	System.out.println("Found " + collector.getTotalHits() +   
                " document(s) (in " + (end - start) +   
                " milliseconds) that matched query '" +   
                searchstr + "':");   
    }
    
    return idList;
  }
  
  
  /**  
  * 根据信息分类和关键词进行查询  
  * @param type,资源的类型,其值为news或product  
  * @param searchKey,搜索的关键字  
  * @return Hits  
  */  
  public ArrayList<String> executeSearchForIdList(File indexDir,String kind,String keyword)   
  {   
	//Analyzer analyzer = new IKAnalyzer(); 
	ArrayList<String> idList = new ArrayList<String>();
	ScoreDoc[] result = null;   
	String fieldName = FIELD_NAME;
    if(keyword != null && !keyword.equals(""))   
    {   
      try    
      {   
    	  //实例化搜索器      
    	  IndexSearcher isearcher = new  IndexSearcher(FSDirectory.open(indexDir),true);//read-only   
          //在索引器中使用IKSimilarity相似度评估器   
          isearcher.setSimilarity(new IKSimilarity());   
             
         // String keyword = "中文分词工具包";   
             
          //使用IKQueryParser查询分析器构造Query对象   
          Query query = IKQueryParser.parse(fieldName, keyword);   
          
          TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM , false);//有变化的地方   
          long start = new Date().getTime();// start time  
          
          //搜索相似度最高的100条记录   
          TopDocs topDocs = isearcher.search(query , 100);
          
          //System.out.println("命中：" + topDocs.totalHits);   
          //输出结果   
          result = topDocs.scoreDocs; 
          
          
         // System.out.println(result.length);   
          for (int i = 0; i < result.length; i++) { 
              Document doc = isearcher.doc(result[i].doc);//new method is.doc()
           // 若debug模式开启，则输出debug 信息
              if (logger.isDebugEnabled()) {
            	  System.out.println(doc.getField("id")+"   "+result[i].toString()+"  ");   
                  System.out.println(doc.getField("id").stringValue()+"   "+result[i].toString()+"  "); 
              }
              
              idList.add(doc.getField("id").stringValue());
          }   
          long end = new Date().getTime();//end time   
        
       // 若debug模式开启，则输出debug 信息
          if (logger.isDebugEnabled()) {
        	  System.out.println("Found " + collector.getTotalHits() +   
                      " document(s) (in " + (end - start) +   
                      " milliseconds) that matched query '" +   
                      keyword + "':");   //*/
          }
          
          
      } catch (Exception e)   
      {   
        e.printStackTrace();   
      }   
    }   
    return idList;   
  }  
  
  
  
  /**反回查询结果  
   * @param indexDir  
   * @param q  
   * @throws Exception  
   */  
    public ArrayList<SearcherBean> selectSearchResult(ArrayList<String> idList,int beginPageNum,int pageSize) {
    	
    	ArrayList<SearcherBean> resultList = null;
    	if(idList.size() == 0){
    		return null;
    	}
    	SqlMachine sqlMachine = new SqlMachine(conn);
    	ResultSet resultSet = sqlMachine.QueryRow(ReleaseTB.TABLE_NAME, ReleaseTB.RELEASE_ID, idList,beginPageNum,pageSize);
    	
    	if(resultSet != null){
			try {
				
				resultList = new ArrayList<SearcherBean>();
				while(resultSet.next()){
					SearcherBean searcherBean = new SearcherBean();
					
					searcherBean.setId(resultSet.getString(ReleaseTB.RELEASE_ID));
					searcherBean.setDate(resultSet.getString(ReleaseTB.RELEASE_MD_DATE));
					searcherBean.setTitle(resultSet.getString(ReleaseTB.RELEASE_SUBJECT));
					searcherBean.setImage(resultSet.getString(ReleaseTB.RELEASE_IMAGE));
					
					String content = Validate.htmlLabelFilter(resultSet.getString(ReleaseTB.RELEASE_CONTEXT));
					content = Validate.htmlFilter(content);
					
					if(content.length() >=200 ){
						content = content.substring(0, 200) + "...";
					}
					
					searcherBean.setContent(content);
				
					resultList.add(searcherBean);
				}
				resultSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    	
    	return resultList;
  	 
    }
    
    /**  
     * 根据信息分类和关键词进行查询  
     * @param type,资源的类型,其值为news或product  
     * @param searchKey,搜索的关键字  
     * @return Hits  
     */  
     public ArrayList<SearcherBean> selectSearchList(File indexDir,String kind,String keyword)   
     {   
   	//Analyzer analyzer = new IKAnalyzer(); 
   	ArrayList<SearcherBean> seracherList = new ArrayList<SearcherBean>();
   	ScoreDoc[] result = null;   
   	String fieldName = FIELD_NAME;
       if(keyword != null && !keyword.equals(""))   
       {   
         try    
         {   
       	  //实例化搜索器      
       	  IndexSearcher isearcher = new  IndexSearcher(FSDirectory.open(indexDir),true);//read-only   
             //在索引器中使用IKSimilarity相似度评估器   
             isearcher.setSimilarity(new IKSimilarity());   
                
            // String keyword = "中文分词工具包";   
                
             //使用IKQueryParser查询分析器构造Query对象   
             Query query = IKQueryParser.parse(fieldName, keyword);   
             
             TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM , false);//有变化的地方   
             long start = new Date().getTime();// start time  
             
             //搜索相似度最高的100条记录   
             TopDocs topDocs = isearcher.search(query , 100);
             
             //System.out.println("命中：" + topDocs.totalHits);   
             //输出结果   
             result = topDocs.scoreDocs; 
             
             
            // System.out.println(result.length);   
             for (int i = 0; i < result.length; i++) { 
                 Document doc = isearcher.doc(result[i].doc);//new method is.doc()
              // 若debug模式开启，则输出debug 信息
                 if (logger.isDebugEnabled()) {
               	  	 System.out.println(doc.getField("id")+"   "+result[i].toString()+"  ");   
                     System.out.println(doc.getField("id").stringValue()+"   "+result[i].toString()+"  "); 
                 }
                 SearcherBean searcherBean= new SearcherBean();
                 searcherBean.setId(doc.getField("id").stringValue());
                 searcherBean.setContent(doc.getField("content").stringValue());
                 searcherBean.setKind(doc.getField("kind").stringValue());
                 searcherBean.setTitle(doc.getField("title").stringValue());
                 searcherBean.setHtmlcode(doc.getField("htmlcode").stringValue());
                 searcherBean.setIntroduction(doc.getField("introduction").stringValue());
                 searcherBean.setImage(doc.getField("image").stringValue());
                 searcherBean.setDate(doc.getField("date").stringValue());
                 searcherBean.setUrl(doc.getField("url").stringValue());
                 
                 seracherList.add(searcherBean);
             }   
             long end = new Date().getTime();//end time   
           
          // 若debug模式开启，则输出debug 信息
             if (logger.isDebugEnabled()) {
           	  System.out.println("Found " + collector.getTotalHits() +   
                         " document(s) (in " + (end - start) +   
                         " milliseconds) that matched query '" +   
                         keyword + "':");   //*/
             }
             
             
         } catch (Exception e)   
         {   
           e.printStackTrace();   
         }   
       }   
       return seracherList;   
     } 
     
     /**  
      * 根据信息分类和关键词进行查询  
      * @param type,资源的类型,其值为news或product  
      * @param searchKey,搜索的关键字  
      * @return Hits  
      */  
      public ArrayList<SearcherBean> selectSearchList(File indexDir,String kind,String keyword,int beginPageNum,int pageSize)   
      {   
    	//Analyzer analyzer = new IKAnalyzer(); 
    	ArrayList<SearcherBean> seracherList = new ArrayList<SearcherBean>();
    	//seracherList.size()=0;
    	ScoreDoc[] result = null;   
    	String fieldName = FIELD_NAME;
        if(keyword != null && !keyword.equals(""))   
        {   
          try    
          {   
        	  //实例化搜索器      
        	  IndexSearcher isearcher = new  IndexSearcher(FSDirectory.open(indexDir),true);//read-only   
              //在索引器中使用IKSimilarity相似度评估器   
              isearcher.setSimilarity(new IKSimilarity());   
                 
             // String keyword = "中文分词工具包";   
                 
              //使用IKQueryParser查询分析器构造Query对象   
              Query query = IKQueryParser.parse(fieldName, keyword);   
              
              TopScoreDocCollector collector = TopScoreDocCollector.create(TOP_NUM , false);//有变化的地方   
              long start = new Date().getTime();// start time  
              
              //搜索相似度最高的100条记录   
              TopDocs topDocs = isearcher.search(query , 100);
              
              //System.out.println("命中：" + topDocs.totalHits);   
              //输出结果   
              result = topDocs.scoreDocs; 
             
              int countRow = result.length;
              if(countRow > (pageSize+beginPageNum)){
            	  pageSize = countRow;
              }else{
            	  pageSize = beginPageNum + pageSize;
              }
             // System.out.println(result.length);
              
              
              for (int i = beginPageNum; i < pageSize; i++) { 
                  Document doc = isearcher.doc(result[i].doc);//new method is.doc()
               // 若debug模式开启，则输出debug 信息
                  if (logger.isDebugEnabled()) {
                	  System.out.println(doc.getField("id")+"   "+result[i].toString()+"  ");   
                      System.out.println(doc.getField("id").stringValue()+"   "+result[i].toString()+"  "); 
                  }
                  SearcherBean searcherBean= new SearcherBean();
                  searcherBean.setId(doc.getField("id").stringValue());
                  searcherBean.setContent(doc.getField("content").stringValue());
                  searcherBean.setKind(doc.getField("kind").stringValue());
                  searcherBean.setTitle(doc.getField("title").stringValue());
                  searcherBean.setHtmlcode(doc.getField("htmlcode").stringValue());
                  searcherBean.setIntroduction(doc.getField("introduction").stringValue());
                  searcherBean.setImage(doc.getField("image").stringValue());
                  searcherBean.setDate(doc.getField("date").stringValue());
                  searcherBean.setUrl(doc.getField("url").stringValue());
                  
                  seracherList.add(searcherBean);
              }   
              long end = new Date().getTime();//end time   
            
           // 若debug模式开启，则输出debug 信息
              if (logger.isDebugEnabled()) {
            	  System.out.println("Found " + collector.getTotalHits() +   
                          " document(s) (in " + (end - start) +   
                          " milliseconds) that matched query '" +   
                          keyword + "':");   //*/
              }
              
              
          } catch (Exception e)   
          {   
            e.printStackTrace();   
          }   
        }   
        return seracherList;   
      }
      
     public int getSearcherRow(File indexDir,String kind,String keyword){
    	 int countRow = 0;
    	
     	ScoreDoc[] result = null;   
     	String fieldName = FIELD_NAME;
         if(keyword != null && !keyword.equals(""))   
         {   
           try    
           {   
         	  //实例化搜索器      
         	  IndexSearcher isearcher = new  IndexSearcher(FSDirectory.open(indexDir),true);//read-only   
               //在索引器中使用IKSimilarity相似度评估器   
               isearcher.setSimilarity(new IKSimilarity());   
                  
              // String keyword = "中文分词工具包";   
                  
               //使用IKQueryParser查询分析器构造Query对象   
               Query query = IKQueryParser.parse(fieldName, keyword);   
        
               
               //搜索相似度最高的100条记录   
               TopDocs topDocs = isearcher.search(query , 100);
               
               //System.out.println("命中：" + topDocs.totalHits);   
               //输出结果   
               result = topDocs.scoreDocs; 
               countRow = result.length;
           }catch (Exception e)   
           {   
               e.printStackTrace();   
             }  
         }
    	 
    	 return countRow;
     }
    
  public BooleanQuery getBooleanQuery(String q){
	  BooleanQuery query = new BooleanQuery();
	  if(q.contentEquals(" ")){
		  String[] s = q.split(" "); 
		  for(String q1:s){
			  Query queryTemp = new TermQuery(new Term("context", q1)); 
			  query.add(queryTemp, BooleanClause.Occur.MUST);
		  }
	  } 
	  
	  
	  return query;
	  
  }
}  
